package com.dmall.chapter05.section04;

import com.dmall.chapter02.section09.Graph;
import java.util.*;

/**
 * 基于广度优先遍历的单源路径问题优化
 * 提前终止
 * @author wx
 * @date 2020-02-27 21:33:40
 */
public class Path {

    private Graph G;
    private int s, t;
    private boolean[] visited;
    private int[] pre;

    public Path(Graph G, int s, int t) {
        G.validateVertex(s);
        G.validateVertex(t);
        this.G = G;
        this.s = s;
        this.t = t;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        for (int i = 0; i < pre.length; i++) {
            pre[i] = -1;
        }

        bfs(s);
        for(boolean e: visited)
            System.out.print(e + " ");
        System.out.println();
    }

    private void bfs(int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;
        pre[s] = s;
        if (s == t) {
            return;
        }
        while (!queue.isEmpty()) {
            int v = queue.remove();

            for (int w : G.adj(v)) {
                if (!visited[w]) {
                    queue.add(w);
                    visited[w] = true;
                    pre[w] = v;
                    if (w == t) {
                        return;
                    }
                }
            }
        }
    }

    public boolean isConnected() {
        return visited[t];
    }

    public Iterable<Integer> path() {
        List<Integer> res = new ArrayList<>();
        if (!isConnected()) {
            return res;
        }
        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filename = Path.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);

        Path path1 = new Path(g, 0, 6);
        System.out.println("0 -> 6 : " + path1.path());

        Path path2 = new Path(g, 0, 1);
        System.out.println("0 -> 1 : " + path2.path());

        Path path3 = new Path(g, 0, 5);
        System.out.println("0 -> 5 : " + path3.path());

        Path path4 = new Path(g, 0, 0);
        System.out.println("0 -> 0 : " + path4.path());
    }
}
